package com.hqyj.config;

import com.hqyj.realm.MyRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
/*1.ShiroFilterFactoryBean*/
    @Bean(name="shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

        // <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->

        filterChainDefinitionMap.put("/goLogin", "anon");      //放行登录界面
        filterChainDefinitionMap.put("/index", "anon");     //这是放行index主界面
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/a","anon");


        filterChainDefinitionMap.put("/bootstrap-4.5.0-dist/**","anon");
        filterChainDefinitionMap.put("/image/**","anon");
        filterChainDefinitionMap.put("/jpg/**","anon");
        filterChainDefinitionMap.put("/loginStatic/**","anon");
        filterChainDefinitionMap.put("/qianduanStaticResource/**","anon");

//        filterChainDefinitionMap.put("/css/**", "anon");
//        filterChainDefinitionMap.put("/fonts/**", "anon");
//        filterChainDefinitionMap.put("/images/**", "anon");
//        filterChainDefinitionMap.put("/js/**", "anon");
//        filterChainDefinitionMap.put("/flexslider/**","anon");
//        filterChainDefinitionMap.put("/google-code-prettify/**","anon");
//        filterChainDefinitionMap.put("/portfolio/**","anon");
//        filterChainDefinitionMap.put("/quicksand/**","anon");

        filterChainDefinitionMap.put("/mianban", "authc");
        // 主要这行代码必须放在所有权限设置的最后，不然会导致所有 url 都被拦截 剩余的都需要认证
        //filterChainDefinitionMap.put("/**", "authc");

        // 自动跳去登录的地址
        shiroFilterFactoryBean.setLoginUrl("/goLogin");
        // 未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean(name="securityManager")
    public DefaultWebSecurityManager securityManager(@Qualifier("MyRealm")MyRealm myRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        return securityManager;
    }

    @Bean(name="MyRealm")
    public MyRealm myRealm(){
        return new MyRealm();
    }
}
